package com.example.config.security;


import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dao.UserMapper;
import com.example.entity.User;
import com.example.entity.dto.DtoUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class UserAuthorization implements UserDetailsService {
       @Autowired
       private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("id","username","password");
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);
        if(Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        Set<DtoUser> dtoUsers = userMapper.queryRole(username);
        ArrayList<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (DtoUser dtoUser : dtoUsers) {
            SimpleGrantedAuthority simpleGrantedAuthority =
                    new SimpleGrantedAuthority(dtoUser.getPermissionValue());
            simpleGrantedAuthorities.add(simpleGrantedAuthority);
        }

        return new LoginUser(user,simpleGrantedAuthorities);
    }


}
